package com.sina.shop.manage.dao.order;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.order.Order;
import com.sina.shop.domain.order.Order_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-01-12-16:09
 */
@Repository("orderManageDao")
public class OrderManageDaoImpl extends ShopDataSourceDao implements OrderManageDao {

    @Override
    public int deleteOrder(Long id) {
        return 0;
    }

    @Override
    public List<Map<String, Object>> getOrderList(Order order) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Order> root = criteriaQuery.from(Order.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    orderSelection(root)
            );

            Predicate predicate = orderPredicate(order, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Order_.card)),
                    builder.asc(root.get(Order_.id))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (order.getPage() - 1) * order.getRows();

            query.setFirstResult(first);
            query.setMaxResults(order.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getOrderCount(Order order) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Order> root = criteriaQuery.from(Order.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Order_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    orderPredicate(order, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param order
     * @param builder
     * @param root
     * @return
     */
    protected Predicate orderPredicate(Order order, CriteriaBuilder builder
            , Root<Order> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (order.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Order_.id), order.getLastId())
            );
        }

        if (order.getCard() != null) {
            list.add(
                    builder.equal(root.get(Order_.card), order.getCard().getId())
            );
        }

        if (order.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Order_.createTime), order.getCreateStart())
            );
        }

        if (order.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Order_.createTime), order.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> orderSelection(Root<Order> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Order_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Order_.orderNo).alias("orderNo"));
        list.add(root.get(Order_.card).alias("card"));
        list.add(root.get(Order_.createTime).alias("createTime"));
        list.add(root.get(Order_.payTime).alias("payTime"));

        list.add(root.get(Order_.status).alias("status"));

        return list;
    }
}
